package com.matto1990.app.madlab.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.matto1990.app.madlab.R;
import com.matto1990.app.madlab.provider.MadlabContract.Events;
import com.matto1990.app.madlab.provider.MadlabContract.Meetups;
import com.matto1990.app.madlab.util.NotifyingAsyncQueryHandler;
import com.matto1990.app.madlab.util.TitlebarActivity;
import com.matto1990.app.madlab.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class EventDetailActivity extends TitlebarActivity implements AsyncQueryListener {
    private static final String TAG = "Madlab";
    
    private Context context;
    private NotifyingAsyncQueryHandler handler;
    
    private Gallery meetupGalleryList;
    private TextView eventTitle;
    private TextView eventInterested;
    private Button interestedButton;
    
    private MeetupsAdapter meetupAdapter;
    private Cursor eventCursor;
    private Uri eventUri;
    private Uri meetupUri;
    
    private Date today;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set the layout
        setContentView(R.layout.activity_event_detail);
        
        // Setup the title bar UI
        setupTitlebar();
        
        // Setup a data object for the start of today
        today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setMinutes(0);
        
        // Get the views
        meetupGalleryList = (Gallery) findViewById(R.id.event_meetups_list);
        eventTitle = (TextView) findViewById(R.id.event_title);
        eventInterested = (TextView) findViewById(R.id.event_interested);
        interestedButton = (Button) findViewById(R.id.event_btn_interested);
        
        // Set the meetup listview adapter
        meetupAdapter = new MeetupsAdapter(context);
        meetupGalleryList.setOnItemClickListener(itemClickListener);
        meetupGalleryList.setAdapter(meetupAdapter);
        
        // Setup the interested button onClick
        interestedButton.setOnClickListener(interestedListener);
        
        // Get the application context and content uris
        context = getApplicationContext();
        final Intent intent = getIntent();
        eventUri = intent.getData();
        meetupUri = Events.buildMeetupsUri(Events.getEventId(eventUri));
        Log.i(TAG, "Meetups uri:" + meetupUri);
        
        // Start background query to load events
        handler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
        handler.startQuery(EventQuery._TOKEN, eventUri, EventQuery.PROJECTION);
        handler.startQuery(MeetupsQuery._TOKEN, meetupUri, MeetupsQuery.PROJECTION, Meetups.DEFAULT_SORT);
    }
    
    @Override
    public void onQueryComplete(int token, Object cookie, Cursor cursor) {
        switch (token) {
        case EventQuery._TOKEN:
            if (cursor.getCount() > 0) {
                eventCursor = cursor;
                // Move to the first (and only) position
                cursor.moveToFirst();
                // Get the view contents in the header
                eventTitle.setText(cursor.getString(cursor.getColumnIndex(Events.EVENT_TITLE)));
                // Set the interested text
                final boolean interested = cursor.getInt(cursor.getColumnIndex(Events.EVENT_INTERESTED)) == 1;
                String interestedText;
                if (interested)
                    interestedText = "You are interested";
                else
                    interestedText = "You are not interested"; 
                eventInterested.setText(interestedText);
            }
            else {
                // TODO: Handle this properly
                Log.w("Madlab", "Unknown eventid");
            }
            break;
        case MeetupsQuery._TOKEN:
            // Start managing the cursor and set our adapter to use it
            startManagingCursor(cursor);
            meetupAdapter.changeCursor(cursor);
            
            // Find the right view to set as default (the first upcoming one or last past event)
            // Setup the date formatter
            final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // Boolean to tell when the first upcming even has been found
            boolean foundFirstUpcoming = false;
            // Loop through cursor until first upcoming found or last past event
            while (!cursor.isLast() && !foundFirstUpcoming) {
                // Move to next cursor position
                cursor.moveToNext();
                
                try {
                    // Get the start date and check if it's after the start of today
                    foundFirstUpcoming = sqlDateFormat.parse(cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_START_DATETIME))).after(today);
                }
                catch (ParseException e) {
                    Log.w(TAG, "Incorrect date format", e);
                }
            }
            // Set the current position as the position of the gallery
            meetupGalleryList.setSelection(cursor.getPosition());
            
            break;
        }
    }
    
    // A click listener for the items in the calendar list
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Get the item from the cursor in this position
            final Cursor cursor = (Cursor) meetupAdapter.getItem(position);
            // Get the event id
            final String meetupId = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_ID));
            // Build a url for that specific event
            final Uri meetupUri = Meetups.buildMeetupUri(meetupId);
            // Make an intent to launch that uri
            final Intent intent = new Intent(Intent.ACTION_VIEW, meetupUri);
            // Send the state
            intent.putExtra(STATE, state);
            // Start the activity
            startActivity(intent);
        }
    };
    
    private OnClickListener interestedListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            eventCursor.moveToFirst();
            
            // Get the current value of interested
            final boolean interested = eventCursor.getInt(eventCursor.getColumnIndex(Events.EVENT_INTERESTED)) == 1;
            
            // Set up a content vlaues to change it to the oposite
            final ContentValues values = new ContentValues();
            values.put(Events.EVENT_INTERESTED, !interested);
            
            // Make the change
            getContentResolver().update(eventUri, values, null, null);
            
            Log.i("Madlab", "Updated interested");
            
            // Requery
            handler.startQuery(EventQuery._TOKEN, eventUri, EventQuery.PROJECTION);
        }
    };
    
    // Events adapter uses a cursor to display the data from the content uri
    private class MeetupsAdapter extends CursorAdapter {
        public MeetupsAdapter(Context context) {
            super(context, null);
        }

        /** {@inheritDoc} */
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return getLayoutInflater().inflate(R.layout.list_item_meetup_calendar, parent, false);
        }

        /** {@inheritDoc} */
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Setup some date formats
            final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final SimpleDateFormat monthDateFormat = new SimpleDateFormat("MMM yy");
            final SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
            
            // Get the views
            final TextView startDateMonthView = (TextView) view.findViewById(R.id.meetup_start_date_month);
            final TextView startDateDayView = (TextView) view.findViewById(R.id.meetup_start_date_day);
            final ImageView meetupAttendingView = (ImageView) view.findViewById(R.id.meetup_attending_image);
            
            try {
                // Setup the nice date text
                final String startDate = cursor.getString(cursor.getColumnIndex(Meetups.MEETUP_START_DATETIME));
                
                // Set the view contents
                startDateMonthView.setText(monthDateFormat.format(sqlDateFormat.parse(startDate)));
                if (sqlDateFormat.parse(startDate).before(today)) {
                    startDateMonthView.setBackgroundColor(R.color.title_background);
                }
                startDateDayView.setText(dayDateFormat.format(sqlDateFormat.parse(startDate)));
                
                // Set the interested text
                final boolean attending = cursor.getInt(cursor.getColumnIndex(Meetups.MEETUP_ATTENDING)) == 1;
                if (attending) {
                    meetupAttendingView.setVisibility(View.VISIBLE);
                }
                else {
                    meetupAttendingView.setVisibility(View.GONE);
                }
            } catch (ParseException e) {
                Log.w(TAG, "Incorrect date format", e);
            }
            
            
        }
    }
    
    /** {@link Event} query parameters. */
    private interface EventQuery {
        int _TOKEN = 0;
        
        String[] PROJECTION = {
                BaseColumns._ID,
                Events.EVENT_ID,
                Events.EVENT_TITLE,
                Events.EVENT_DESCRIPTION,
                Events.EVENT_INTERESTED 
        };
    }
    
    /** {@link Meetups} query parameters. */
    private interface MeetupsQuery {
        int _TOKEN = 1;
        
        String[] PROJECTION = {
                "meetups." + BaseColumns._ID,
                Meetups.MEETUP_ID,
                Meetups.MEETUP_TITLE,
                Meetups.MEETUP_START_DATETIME,
                Meetups.MEETUP_ATTENDING
        };
    }
}
